import { getToken, setToken } from '@/utils/auth'
import { login, getUserInfo, getUserInfo1 } from '@/api/user'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    setToken(state, token) {
      // 保存token
      state.token = token
      // 设置持久化
      setToken(token)
    },
    setUserInfo(state, info) {
      state.userInfo = info
    }
  },
  actions: {
    // 登录
    async login(context, data) {
      const res = await login(data)
      context.commit('setToken', res.data)
    },
    // 获取用户信息
    async getUserInfo(context) {
      const result = await getUserInfo()
      const result1 = await getUserInfo1(result.data.userId)
      context.commit('setUserInfo', { ...result.data, ...result1.data })
      return result
    },
    logout(context) {
      context.commit('setUserInfo', {})
      context.commit('setToken', '')
      resetRouter() // 退出重置路由
    }
  }
}
